<?php
class ImageHelper
{
	//错误信息
	public static $msg = [];

	/**
	 * 根据图片路径创建一个图片对象并获取图片信息一起返回
	 * @param string $imagePath 源图片路径
	 * @return array|NULL
	 */
	public static function createImage(string $imagePath = "")
	{
		if (!file_exists($imagePath)) {
			self::$msg[] = "{$imagePath} 文件不存在";
			return NULL;
		}

		$info = getimagesize($imagePath);
		$image['width'] = $info[0];
		$image['height'] = $info[1];
		$image['bits'] = $info['bits'];
		$image['mime'] = $info['mime'];
		if ($image['mime'] === 'image/jpeg') {
			$image['GdImage'] = imagecreatefromjpeg($imagePath);
		} else if ($image['mime'] === 'image/png') {
			$image['GdImage'] = imagecreatefrompng($imagePath);
		} else {
			self::$msg[] = "不支持{$image['mime']}格式";
			return NULL;
		}
		return $image;
	}

	/**
	 * 获取背景色
	 * @desc 获取图片四个角的小矩形的四个角的色值，防止主图信息从四个边框的相对中间位置往内延申
	 * @param array   $image self::createImage返回的数组
	 * @param integer $persent 四角小矩形高宽占总高宽的百分比
	 * @return array 获取到的背景颜色
	 */
	public static function getBackgroundColors(array $image, int $persent = 10)
	{

		$x = floor($image['width'] * $persent / 100);
		$y = floor($image['height'] * $persent / 100);

		$image['width'] -= 1;
		$image['height'] -= 1;

		//左上角正方形四个点位
		$colors[] = imagecolorat($image['GdImage'], 0, 0);
		$colors[] = imagecolorat($image['GdImage'], $x, 0);
		$colors[] = imagecolorat($image['GdImage'], $x, $y);
		$colors[] = imagecolorat($image['GdImage'], 0, $y);

		// // 左下角正方形四个点位
		$colors[] = imagecolorat($image['GdImage'], 0, $image['height'] - $x);
		$colors[] = imagecolorat($image['GdImage'], 0, $image['height']);
		$colors[] = imagecolorat($image['GdImage'], $x, $image['height'] - $y);
		$colors[] = imagecolorat($image['GdImage'], $x, $image['height']);

		//右上角正方形四个点位
		$colors[] = imagecolorat($image['GdImage'], $image['width'] - $x, 0);
		$colors[] = imagecolorat($image['GdImage'], $image['width'] - $x, $y);
		$colors[] = imagecolorat($image['GdImage'], $image['width'], $y);
		$colors[] = imagecolorat($image['GdImage'], $image['width'], 0);

		//右下角正方形四个点位
		$colors[] = imagecolorat($image['GdImage'], $image['width'], $image['height']);
		$colors[] = imagecolorat($image['GdImage'], $image['width'], $image['height'] - $y);
		$colors[] = imagecolorat($image['GdImage'], $image['width'] - $x, $image['height']);
		$colors[] = imagecolorat($image['GdImage'], $image['width'] - $x, $image['height'] - $y);

		return array_unique($colors);
	}

	/**
	 * 通过网格的方式获取色值
	 * @desc 获取图片出现的最多的颜色
	 * @param array   $image self::createImage返回的数组
	 * @param integer $limit_num 获取出现次数最多的颜色的前几个
	 * @param integer $avg 网格数，avg的平方数即为最多获取图片颜色的点数 
	 * @return void
	 */
	public static function getMostColors(array $image, $limit_num = 1, int $avg = 10)
	{
		$skip_x = floor($image['width'] / $avg);
		$skip_y = floor($image['height'] / $avg);
		$colors = [];
		for ($x = 0; $x < $image['width']; $x = $x + $skip_x) {
			for ($y = 0; $y < $image['height']; $y = $y + $skip_y) {
				$colors[] = imagecolorat($image['GdImage'], $x, $y);
			}
		}
		$colors = array_count_values($colors);
		arsort($colors);
		return array_keys(array_slice($colors, 0, $limit_num, true));
	}

	/**
	 * 根据默认设置移除图片背景	 
	 * @param string  $sourceImagePath 源图片路径
	 * @param string  $outputImagePath 目的图片路径
	 * @param boolean $saveSourceImage 是否保存原图片 默认保存
	 * @param integer $fuzz fuzz
	 * @return bool
	 */
	public static function autoRemoveBg(string $sourceImagePath, string $outputImagePath, $saveSourceImage = true, int $fuzz = 10)
	{
		$image = self::createImage($sourceImagePath);
		if ($image === NULL) return false;

		$colors =  array_unique(array_merge(
			self::getBackgroundColors($image, 10),
			self::getMostColors($image, 1, 10),
		));

		return self::removeBg($sourceImagePath, $outputImagePath, $colors, $saveSourceImage, $fuzz);
	}

	public static function removeBg(string $sourceImagePath, string $outputImagePath, array $colors = [], $saveSourceImage = true, int $fuzz = 10)
	{
		if (!file_exists($sourceImagePath)) return false;

		if(strtolower(substr($outputImagePath,-3)) !== "png") $outputImagePath .= '.png';

		exec(($saveSourceImage === true ? 'cp' : 'mv') . " $sourceImagePath $outputImagePath");
		foreach ($colors as $color) {
			exec(
				sprintf(
					"convert %s -fuzz %d%% -transparent 'rgba(%d,%d,%d,1)' %s",
					$outputImagePath,
					10,
					($color >> 16) & 0xFF,
					($color >> 8) & 0xFF,
					$color & 0xFF,
					$outputImagePath
				)
			);
			//调整背景颜色
			// exec("convert $imagePath -background white -alpha remove -alpha off $imagePath");
			// echo $imagePath, PHP_EOL;
			//改变颜色
			// convert logo_ok/9.png -separate -swap 1,0 -combine  logo_ok/9_1.png 
		}

		return true;
	}
}

$images = scandir('logo');
foreach ($images as $image) {
	if (substr($image, 0, 1) !== '.') {
		ImageHelper::autoRemoveBg("logo/{$image}", "logo_ok/{$image}");
	}
}

exit;
ImageHelper::removeBg('logo/logoquan16220730524.jpg', 'logo_ok/logoquan16220730524.png');
